<?php

namespace App\Console\Commands;

use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderRemark;
use App\Models\OrderLease;
use App\Models\OrderGoods;
use App\Models\Goods;
use App\Models\GoodsSetmeal;
use App\Models\GoodsSpec;
use App\Models\AuthenticLog;
use App\Models\OrderReturn;
use App\Models\OtherOrder;
use App\Services\GoodsService;
use App\Services\RadarService;
use App\Services\OrderService;
use App\Services\AlipayService;
use App\Services\YpcreditService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use App\Models\OtherOrderAllocate;
class OtherBeiKeOrderSyncCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'otherBeiKeOrderSync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '贝壳外部订单同步任务';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {

//        $res = RadarService::getBeiKeOtherOrder();
//        if($res['code']=='200') { //成功
//            foreach ($res['data'] as $data) {
//                $orderId=Order::where('trade_no',$data['order_no'])->where('seller_id','1704471788')->value('id');
//                if($orderId){
//                    $order_data=$data;
//                    if($order_data['status']==7||$order_data['status']==10){
//                        $order_status = 30;
//                    }else if($order_data['status']==6){
//                        $order_status = 60;
//                    }else if($order_data['status']==9){
//                        $order_status = 4;
//                    }else if($order_data['status']==0){
//                        $order_status = 1;
//                    }else if($order_data['status']==1){
//                        $order_status = 3;
//                    }else if($order_data['status']==4){
//                        $order_status = 10;
//                    }else if($order_data['status']==5){
//                        $order_status = 20;
//                    }else{
//                        $order_status=1;
//                    }
//                    if($order_data['is_timeout']=='1'){
//                        $order_status = 39;
//                    }
//                   Order::where('id',$orderId)->update(['status'=>$order_status]);
//
//
////                    $add_remark = [
////                        'uid'=>'23',
////                        'username'=>'紧急联系人',
////                        'create_time'=>time(),
////                        'remark'=>$data['kf_remark'],
////                        'order_id'=>$orderId
////                    ];
////                    OrderRemark::insert($add_remark);
////                    dd($data['order_no']);
//
//                        $order_lease_datas = $data['billList'];
//                        $OrderLease=OrderLease::where('order_id',$orderId)->get()->toArray();
//
//                        foreach($order_lease_datas as $order_lease_data){
//                            $status=0;
//                            if($order_lease_data['status']==1){
//                                $status = 1;
//                            }else if($order_lease_data['status']==5){
//                                $status = 2;
//                            }
//                            if($status>0&&$order_lease_data['alipay_trade_no']&&$OrderLease){
//                                OrderLease::where('order_id',$orderId)->where('which_period',$order_lease_data['expact'])->update(['status'=>$status,'pay_time'=>$order_lease_data['pay_time']?strtotime($order_lease_data['pay_time']):'']);
//                            }else{
//
//                                if(!$OrderLease){
//                                    $add_order_lease_data = [
//                                        'order_id'=>$orderId,
//                                        'which_period'=>$order_lease_data['expact'],
//                                        'rent'=>$order_lease_data['month_price'],
//                                        'paid_rent'=>$status==1?$order_lease_data['month_price']:0,
//                                        'status'=>$status,
//                                        'begin_time'=>$order_lease_data['pay_date'],
//                                        'end_time'=>bcadd($order_lease_data['pay_date'],86400*30),
//                                        'pay_time'=>$order_lease_data['pay_time']?strtotime($order_lease_data['pay_time']):'',
//                                        'create_time'=>strtotime($order_lease_data['create_time']),
//                                        'alipay_trade_no'=>$order_lease_data['alipay_trade_no']
//                                    ];
//                                    OrderLease::insert($add_order_lease_data);
//                                }
//                            }
//                        }
//                    var_dump($data['order_no']);
//
//
//                }
//            }
//        }   exit();
//   exit();

        $res = RadarService::getBeiKeOtherOrder();
        if($res['code']=='200'){ //成功
            foreach($res['data'] as $data){
                //请求订单数量
                $order_data = $data;

                  if(Redis::get('TradeNoBeiKe'.$order_data['order_no'])){
                     continue;
                  }


                $order_lease_datas = $data['billList'];
                $goods_data = $data['goodsInfo'];
                $member_data = $data['userInfo'];

            if(!empty($order_data) && !empty($goods_data) && !empty($member_data)){
                $imgurl=$this->upload_img($order_data['goodsInfo']['goods_cover']);
//                dd( $imgurl);
                $idcard_front=$this->upload_img($member_data['userid_img']);
                $idcard_back=$this->upload_img($member_data['userid_fimg']);
                $pdf_file_oss=$this->upload_img($order_data['pdf_file_oss']);

                //会员资料
                $cert_no = $member_data['idcard'];
                $member = MemberOther::where('cert_no',$cert_no)->select('id')->first();
                $member = obToArray($member);
                if($member){
                    $uid = $member['id'];
                }else{
                    $add_member_data = [
                        'mobile'=>$member_data['phone'],
                        'user_id'=>isset($member_data['user_id'])?$member_data['user_id']:0,
                        'cert_name'=>$member_data['name'],
                        'cert_no'=>$cert_no,
                        'idcard_front'=>$idcard_front,
                        'idcard_back'=>$idcard_back,
                        'nick_name'=>$member_data['name'],
                        'gender'=>$member_data['gender'],
                        'province'=>$member_data['province'],
                        'city'=>$member_data['city'],
                        'status'=>'1',
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    //ceshi123
                    $uid = MemberOther::insertGetId($add_member_data);//会员ID
                }

                    //商品
                    $add_goods_data = [
                        'title'=>$goods_data['goods_name'],
                        'new_grade'=>0,
                        'member_id'=>'1704471788',
                        'category_id'=>'0',
                        'status'=>'2',
                        'pay_type'=>'1',
                        'ischeck'=>'4',
                        'is_delete'=>'1',
                        'create_time'=>time(),
                        'update_time'=>time(),
                        'is_show'=>'2'
                    ];
                    //ceshi123
                    $goods_id = Goods::insertGetId($add_goods_data);//商品ID
                // }
                //商品套餐
                $add_goods_setmeal_data = [
                    'goods_id'=>$goods_id,
                    'title'=>$goods_data['goods_spec'],
                    'quantity'=>1,
                    'foregift'=>$goods_data['deposit'],
                    'price'=>$goods_data['my_original_market'],
                    'create_time'=>time()
                ];
                //ceshi123
                $setmeal_id = GoodsSetmeal::insertGetId($add_goods_setmeal_data);//商品套餐ID
                //商品套餐详情
                    $add_goods_spec_data = [
                        'lease_time'=>$goods_data['expect']*30,
                        'setmeal_id'=>$setmeal_id,
                        'lease_price'=>$goods_data['month_price'],
                        'withhold_cycle'=>'30',
                        'day_price'=>$goods_data['price_selling'],
                        'goods_id'=>$goods_id
                    ];

                    //ceshi123
                    $spec_id = GoodsSpec::insert($add_goods_spec_data);//商品套餐ID
//                $spec_id=1;
                //订单
                if($order_data['status']==7||$order_data['status']==10){
                    $order_status = 30;
                }else if($order_data['status']==6){
                    $order_status = 60;
                }else if($order_data['status']==9){
                    $order_status = 4;
                }else if($order_data['status']==0){
                    $order_status = 1;
                }else if($order_data['status']==1){
                    $order_status = 3;
                }else if($order_data['status']==4){
                    $order_status = 10;
                }else if($order_data['status']==5){
                    $order_status = 20;
                }else{
                    $order_status=1;
                }
                $scores = array_column($order_lease_datas, 'month_price');
                $totalScore = array_sum($scores);
                $add_order_data = [
                    'seller_id'=>'1704471788',
                    'username'=>'beike',
                    'uid'=>$uid,
                    'trade_no'=>$order_data['order_no'],
                    'is_insurance_choose'=>'',
                    'sign_status'=>2,
                    'pact_url'=>$pdf_file_oss,
                    'rent_total'=>$totalScore,
                    'month_total'=>$order_data['expect'],
                    'amount'=>$order_data['number_goods'],
                    'payment'=>'',
                    'remark'=>'',
                    'realname'=>$order_data['sendInfo']['address_name']??'0',
                    'mobile'=>$order_data['sendInfo']['address_phone']??'0',
                    'address'=>$order_data['sendInfo']['address_content']??'0',
                    'pay_time'=>'',
                    'prov'=>$order_data['sendInfo']['address_province'],
                    'city'=>$order_data['sendInfo']['address_city'],
                    'area'=>$order_data['sendInfo']['address_area'],
                    'begin_time'=>date('Y-m-d H:i:s',strtotime($order_data['create_at'])),
                    'end_time'=>date('Y-m-d H:i:s',strtotime('+ '.$order_data['expect'].'month',strtotime($order_data['create_at']))),
                    'payer_user_id'=>'',
                    'user_email'=>'',
                    'old_order_id'=>$order_data['id'],
                    'status'=>$order_status,
                    'create_time'=>strtotime($order_data['create_at']),
                    'update_time'=>time(),
                    'pay_type'=>'1',
                    'order_from'=>'tingxiangzu-beike',
                    'foregift_deduct'=>'',
                    'foregift_pay'=>''
                ];
                //ceshi123
                $order_id = Order::insertGetId($add_order_data);//订单ID
////                dd($order_id);
//                //ceshi123
//               $res_set = RadarService::setOtherOrder($order_count,$order_data['id']);


                $add_remark = [
                    'uid'=>'23',
                    'username'=>'同步',
                    'create_time'=>time(),
                    'remark'=>'同步sbk订单',
                    'order_id'=>$order_id
                ];
                OrderRemark::insert($add_remark);


                //订单商品
                $add_order_goods_data = [
                    'order_id'=>$order_id,
                    'goods_id'=>$goods_id,
                    'goods_title'=>$goods_data['goods_name'],
                    'imgurl'=>$imgurl,
                    'setmeal_id'=>$setmeal_id,
                    'setmeal_title'=>$goods_data['goods_spec'],
                    'spec_id'=>$spec_id,
                    'lease_set'=>'1',
                    'lease_time'=>$goods_data['expect']*30,
                    'lease_price'=>$goods_data['month_price'],
                    'setmeal_price'=>$order_data['finishedprice'],
                    'setmeal_foregift'=>$order_data['deposit'],
                    'start_date'=>$order_data['start_date'],
                    'pact_type'=>$order_data['finishedprice']>0?'1':'2',
                    'is_buy_out'=>'1',
                    'create_time'=>time(),
                    'device_number'=>$data['serial_number'],
                    'website_price'=>$add_order_data['rent_total'],
                ];
                //ceshi123
                OrderGoods::insert($add_order_goods_data);


                //订单租期
                foreach($order_lease_datas as $order_lease_data){
                    if($order_lease_data['status']==1){
                        $status = 1;
                    }else if($order_lease_data['status']==5){
                        $status = 2;
                    }else{
                        $status=0;
                    }
                    $add_order_lease_data = [
                        'order_id'=>$order_id,
                        'which_period'=>$order_lease_data['expact'],
                        'rent'=>$order_lease_data['month_price'],
                        'paid_rent'=>$status==1?$order_lease_data['month_price']:0,
                        'status'=>$status,
                        'begin_time'=>$order_lease_data['pay_date'],
                        'end_time'=>bcadd($order_lease_data['pay_date'],86400*30),
                        'pay_time'=>$order_lease_data['pay_time']?strtotime($order_lease_data['pay_time']):'',
                        'create_time'=>strtotime($order_lease_data['create_time']),
                        'alipay_trade_no'=>$order_lease_data['alipay_trade_no']
                    ];
                    //ceshi123
                    OrderLease::insert($add_order_lease_data);
                }



                //订单租期下单日开始算
                $authenticLog = AuthenticLog::where('order_id',$order_id)->select('id')->first();
                $authenticLog = obToArray($authenticLog);
                if($authenticLog){
                    //已有认证资料

                }else{
                    $member = MemberOther::where('id',$uid)->first();
                    $member = obToArray($member);
                    //认证资料
                    $add_authentic_data = [
                        'order_id'=>$order_id,
                        'certify_id'=>'1',
                        'status'=>'1',
                        'cert_no'=>$cert_no,
                        'cert_name'=>$member['cert_name'],
                        'idcard_front'=>$member['idcard_front'],
                        'idcard_back'=>$member['idcard_back'],
                        'create_time'=>date('Y-m-d H:i:s')
                    ];
                    //ceshi123
                    AuthenticLog::insert($add_authentic_data);
                }

                $OrderReturn=OrderReturn::where('order_id',$order_id)->value('id');
                if(!$OrderReturn){
                    $filesimg=[];
                    $imgs=explode('|',$data['files']['files']);
                    foreach ($imgs as $files){
                        $filesimg[]=$this->upload_img($files);
                    }
                    $data = [
                        'order_id'=>$order_id,
                        'logistics_name'=>'',
                        'logistics_no'=>'',
                        'delivery_type'=>2,
                        'images'=>'',
                        'sign_proof'=>implode(',',$filesimg),
                        'status'=>OrderReturn::ORDER_EXPRESS_STATUS_SIGNED,
                        'type'=>OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY,
                        'create_time'=>time(),
                    ];
                    OrderReturn::insert($data);
                }


                Redis::set('TradeNoBeiKe'.$order_data['order_no'],1);
              }

            }
            $this->infoLog('订单同步任务执行成功',$res['data']);

        }else{ //提示

            $this->infoLog('订单同步任务执行失败',[$res['msg']]);
        }

    }

    public function upload_img($fileUrl){
        $path = parse_url($fileUrl, PHP_URL_PATH);

// 获取路径的文件信息
        $fileName = pathinfo($path, PATHINFO_BASENAME);
        if(!empty($fileName)){
            // echo $fileUrl."\r\n";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname(dirname(dirname(__FILE__)))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
            return $fileName;
            // dd($uploud_res);

        }

    }
}
